<?php

namespace App\Http\Controllers\Api\V1;

use App\Events\GameFinish;
use App\Models\ChildPlay;
use App\Models\Device;
use App\Models\Game;
use App\Models\History;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use mysql_xdevapi\Exception;

class GameController extends BaseController
{
    private $cache_head = "child_play";

    public function index()
    {
        $data = $this->getUser();

        return $this->json([$data], 'success', 2000);
        //return $this->json(['user' => $this->user, 'success', 2000]);
    }

    //训练项目开始时间
    public function start(Request $request)
    {

        $this->validate($request, [
            'start_time' => 'required|integer',
            'code' => 'required|string|exists:games',
            'device_code' => 'required|string|exists:devices,code',
            'child_id' => 'required|integer|exists:children,id'
        ], [], []);

        $data = $request->only(['start_time', 'code', 'device_code', 'child_id']);
        $device  = Device::where(['code'=>$data['device_code'], 'agency_id'=>$this->getUser()->agency_id])->first();
        if (empty($device)){
            return $this->json([],  config("apicode.verifyDeviceFail.msg"), config("apicode.verifyDeviceFail.code"));
        }
        $game = Game::where('code', $data['code'])->first();
        $enableGrades = $device->deviceGrades()->pluck("grade_id")->toArray();
        if(!in_array($game->grade_id, $enableGrades)){
            return $this->json([],  config("apicode.gameInDeviceDisabled.msg"), config("apicode.gameInDeviceDisabled.code"));
        }

        $key = cacheHead($this->cache_head). "_". $data['child_id']. "_". $data['device_code'];

        if ( $lastPlay = Cache::get($key)){
            return $this->json(['game_code'=>$lastPlay['code'], 'last_childplay_id'=>666666], config("apicode.gameIsPlaying.msg"), config("apicode.gameIsPlaying.code"));
        }

        if (Cache::add($key, $data, config('site.other.game_end_unexpectedly_time') * 60)){
            return $this->json(['childplay_id' => 666666]);
        }
        Log::error(Cache::get($key));
        return $this->json([], config("apicode.serverError.msg"), config("apicode.serverError.code"));
    }

    //训练项目结束时间
    public function finish(Request $request)
    {
        $user = $this->getUser();
        $this->validate($request, [
            'code' => 'required|string|exists:games',
            'device_code' => 'required|string|exists:devices,code',
            'child_id' => 'required|integer|exists:children,id',
            'end_time' => 'required|integer',
            'start_star' => 'required|integer',
            'end_star' => 'required|integer',
            'result' => 'required|in:0,1',
            'level' => 'sometimes|integer'
        ], [], []);

        $data = $request->only(['end_time', 'code', 'device_code','level', 'child_id', 'start_star', 'end_star', 'result', 'childplay_id']);
        $data['device_id'] = Device::where("code", $data['device_code'])->value("id");

        $key = cacheHead($this->cache_head)."_".$data['child_id']. "_". $data['device_code'];
        $lastPlay = Cache::get($key, '');
        if (empty($lastPlay)){
            Log::error("game is finish, child_id". $data['child_id']. '; device_code'. $data['device_code']);
            return $this->json([],  config("apicode.gameIsFinish.msg"), config("apicode.gameIsFinish.code"));
        }
        try {
            $game = Game::where('code', $data['code'])->select("id","grade_id","category_id")->first();
            $data['game_id'] = $game->id;
            $data['grade_id'] = $game->grade_id;
            $data['category_id'] = $game->category_id;
            $data['agency_id'] = $user->agency_id;
            $data['user_id'] = $user->id;
            $data['use_time'] = $data['end_time'] - $lastPlay['start_time'];
            $data['start_time'] = date('Y-m-d H:i:s', $lastPlay['start_time']);
            $data['end_time'] = date('Y-m-d H:i:s', $data['end_time']);

            if ( !$history = History::create($data) ){
                return $this->json([], '记录添加失败', config("apicode.serverError.code"));
            }

            Cache::forget($key);
            event(new GameFinish($history));

            return $this->json();

        } catch (Exception $exception) {
            Log::error("finish error");
            Log::error($exception->getMessage());
            return $this->json([], $exception->getMessage(), config("apicode.serverError.code"));
        }

    }
}
